% Function : merge sections(delete outliers)
% Parameter:
%   section: each cell is row vector of endpoints(cell array)
% Return:
%   r: each row is the left and right endpoints of one section(n*2 matrix)
function r = mergeS(section)
    n = numel(section);       % number of section groups

    % when number of section groups less than 3
    if n < 3
        if n == 1
            % repeat vector to 2*n matrix
            t = repmat(section{1}, 2, 1);
        else
            n1 = numel(section{1});
            n2 = numel(section{2});

            if n1 == n2
                t = cell2mat(section);
            elseif n1 < n2
                t = repmat(section{1}, 2, 1);
            else
                t = repmat(section{2}, 2, 1);
            end
        end

        % select the maximum of left endpoints and the minimum of right endpoints
        smax      = max(t);
        smin      = min(t);
        smax(end) = [];
        smin(1)   = [];

        r = [smax', smin'];

        return;
    end

    nEndpoints = zeros(1, n); % number of endpoints for each group
    for i = 1 : n
        nEndpoints(i) = numel(section{i});
    end

    % frequency count for nEndpoints
    % header of table: value count percentage
    tbl = zeros(0, 3);
    tmp = nEndpoints;     % copy of nEndpoints
    i   = 1;              % loop counter

    while ~isempty(tmp)
        tmin = min(tmp);
        lgc  = (tmp == tmin); % selecting logical matrix

        tbl(i, 1) = tmin;
        tbl(i, 2) = sum(lgc);
        tbl(i, 3) = tbl(i, 2) / n;

        tmp(lgc) = [];

        i = i + 1;
    end

    % choose number of sections whose frequency is maximum
    i = find(tbl(:, 2) == max(tbl(:, 2)));
    i = i(1);

    if tbl(i, 3) < 0.5
        error('mergeS: no dominated representative sections');
    end

    irep = find(nEndpoints == tbl(i, 1));   % index of representatives
    nrep = numel(irep);                     % number of representatives

    % delete rather than select is better?
    section = section(irep);
    if isrow(section)
        section = section';
    end
    section = cell2mat(section);  % new sections that is a matrix

    % boxplot statistics: get upper and lower limits of each endpoints
    [Upper, Lower, Q] = Box(section);

    % amend the values that exceed limits
    for i = 1 : nrep
        lgc = (section(i, :) > Upper | section(i, :) < Lower);
        section(i, lgc) = Q(2, lgc);
    end

    % delete representatives that exceeds the limit
    % i = 1;
    % while i <= nrep
    %     if any(section(i, :) > Upper | section(i, :) < Lower)
    %         section(i, :) = [];
    %         irep(i)       = [];
    %         nrep          = nrep - 1;
    %     else
    %         i = i + 1;
    %     end
    % end

    % select the maximum of left endpoints and the minimum of right endpoints
    smax      = max(section);
    smin      = min(section);
    smax(end) = [];
    smin(1)   = [];

    r = [smax', smin'];
end
